<!DOCTYPE html>

<html lang="zh-Hans">
  <head>
    <meta charset="utf-8" />
    <meta name="author" content="rogepi" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="/vue.global.js"></script>
    <title>4-watch-example</title>
  </head>

  <body>
    <div id="watch-example">
      <p>
        Ask a yes/no question:
        <input v-model="question" />
      </p>
      <p>{{answer}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
    <script>
      const watchExampleVM = Vue.createApp({
        data() {
          return {
            question: '',
            answer: 'Questions usually contain a question mark. ;-',
          };
        },
        // Vue 通过 watch 选项提供了一个更通用的方法，来响应数据的变化。
        // 当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的。
        watch: {
          question(newQuestion, oldQuestion) {
            if (newQuestion.indexOf('?') > -1) {
              this.getAnswer();
            }
          },
        },
        methods: {
          getAnswer() {
            this.answer = 'Thinking...';
            axios
              .get('https://yesno.wtf/api')
              .then((response) => {
                this.answer = response.data.answer;
              })
              .catch((error) => {
                this.answer = 'Error! Could not reach the API. ' + error;
              });
          },
        },
      }).mount('#watch-example');
    </script>
  </body>
</html>
